﻿using System.Text.Json;
using OnHook.Common.Extension;

namespace OnHook.Framework.Json
{


    /// <summary>
    /// long行转成字符串
    /// </summary>
    public class EnumStringConverter : System.Text.Json.Serialization.JsonConverter<Enum>
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="typeToConvert"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                return (Enum)(reader.GetString() ?? "").ToEnum(typeToConvert, null!);
            }
            return null!;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }

}
